/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.msg.hrappy.web.servlet;

import edu.msg.hrappy.backend.model.DepartmentType;
import edu.msg.hrappy.backend.model.Job;
import edu.msg.hrappy.backend.model.User;
import edu.msg.hrappy.backend.service.DepartmentTypeService;
import edu.msg.hrappy.backend.service.UserService;
import edu.msg.hrappy.backend.service.exception.ServiceException;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author toroke
 */
public class AddUserServlet extends HttpServlet {

    @EJB
    private UserService msguserService;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.getSession().setAttribute("er", null);

        String address = "./addUser.jsp";

        RequestDispatcher dispatcher = req.getRequestDispatcher(address);

        dispatcher.forward(req, resp);

    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        try {

            String firstName = req.getParameter("firstName");
            String lastName = req.getParameter("lastName");
            String telNumber = req.getParameter("telNumber");
            String mobilNumber = req.getParameter("mobilNumber");
            String email = req.getParameter("email");
            String functionInCompany = req.getParameter("functionInCompany");
            String description = req.getParameter("description");
            String userName = req.getParameter("userName");
            String roleInCompany = req.getParameter("roleInCompany");
            String password = req.getParameter("password");
            User user = new User(firstName, lastName, telNumber, mobilNumber, email, functionInCompany, description, userName, password, roleInCompany);
            msguserService.insert(user);
        } catch (ServiceException | NumberFormatException ex) {
            req.getSession().setAttribute("er", "There was a problem, please try again");
            String address = "./addUser.jsp";

            RequestDispatcher dispatcher = req.getRequestDispatcher(address);

            dispatcher.forward(req, resp);
        }
        req.getSession().setAttribute("er", "User added susseccfully");
        String address = "./addUser.jsp";

        RequestDispatcher dispatcher = req.getRequestDispatcher(address);

        dispatcher.forward(req, resp);
    }
}
